package 多线程07_线程池;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Java 单线程和线程池耗时的对比
 * @ClassName: TestThread01
 * @Author: AllenSun
 * @Date: 2022/3/18 上午1:46
 */
public class TestThread06 {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService1 = Executors.newCachedThreadPool();
        ExecutorService executorService2 = Executors.newFixedThreadPool(10);
        ExecutorService executorService3 = Executors.newSingleThreadExecutor();
        // Long startTime = System.currentTimeMillis();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                10,
                20,
                0L,
                TimeUnit.MICROSECONDS,
                new ArrayBlockingQueue<Runnable>(10));

        try {
            List<String> list = new ArrayList<String>();
            List<FutureTask<String>> futureList = new ArrayList<FutureTask<String>>();
            for (int i = 0; i < 10; i++) {
                FutureTask<String> futureTask = new FutureTask<String>(new MyTask01(i));
                threadPoolExecutor.submit(futureTask);
                futureList.add(futureTask);
            }

            //结果归集
            for (FutureTask<String> future : futureList) {
                while (true) {
                    if (future.isDone()&& !future.isCancelled()) {
                        String result = future.get();//Future特性
                        System.out.println("返回结果为："+result);
                        break;
                    }else {
                        Thread.sleep(1);//避免CPU高速轮循，可以休息一下。
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }


        // System.out.println("时间："+(System.currentTimeMillis()-startTime));
    }
}

class MyTask01 implements Callable {

    int i = 0;

    public MyTask01(int i) {
        this.i=i;
    }

    @Override
    public String call() {
        System.out.println(Thread.currentThread().getName()+"--"+i);
        try {
            //模拟业务逻辑
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName()+"--"+i+"--返回结果";
    }
}
